<?php


namespace app\diy\controller;


use app\ApiRest;
use app\decorate\model\IndexCase;
use app\decorate\model\IndexNews;
use app\decorate\model\IndexSite;
use app\diy\model\DiyModel;
use app\house\controller\IndexHouse;
use app\house\model\AdminBanner;
use app\house\model\AdminCate;
use app\house\model\AdminHouse;

/**
 * 小程序获取diy数据
 * @author ArtizanZhang
 * @DataTime: 2019/12/10 14:33
 * Class WxAppDiyController
 * @package app\diy\controller
 */
class WxAppDiyController extends ApiRest
{





    public function getDiyData()
    {

        $input = $this->_param;

        $key = $this->_param['key'] ?? null;

        $diy_data = DiyModel::where([['status', '=', 1],['uniacid', '=', $this->_uniacid]])->find();

        //根据Key获取当前页面DIY数据
        $page = json_decode($diy_data['page'], true)[$key] ?? [];

        if( (  empty($page)   ||  (array_key_exists('list',$page)  && empty($page['list']) )  ) && $key == 20001 ){

            //By.jingshuixian   默认个人中心三个菜单    临时解决方案
            $defaultPage=<<<DEFAULT
{"list":[{"title":"用户信息","type":"userInfo","icon":"iconyonghuxinxi","isDelete":false,"addNumber":1,"attr":[{"title":"字体颜色","type":"ColorPicker","name":"fontColor"},{"title":"背景图片","type":"UploadImage","desc":"750*440","name":"bgImage"}],"data":{"nickName":"用户昵称","avatarUrl":"https://lbqnyv2.migugu.com/defaultAvatar.png","nickText":"更新我的个人资料","fontColor":"#F9DEAF","bgImage":[{"url":"http://lbqny.migugu.com/admin/diy/user_bg.jpg"}]},"id":1577524949068,"compontents":"ucenterCompoent"},{"title":"创建名片","type":"createCard","icon":"iconchuangjianmingpian","isDelete":false,"addNumber":1,"data":{"createText":"创建我的名片","createBtn":"创建名片"},"id":1577524949787,"compontents":"ucenterCompoent"},{"title":"切换销售","type":"changeStaff","icon":"iconqiehuanmingpian-copy","isDelete":false,"addNumber":1,"attr":[{"title":"模板名称","type":"Input","name":"title"},{"title":"是否显示更多","type":"Switch","name":"isShowMore"}],"data":{"title":"切换销售","isShowMore":true},"dataList":{"id":2661,"fans_id":158,"name":"","avatar":"","job_name":null},"id":1577524950407,"compontents":"ucenterCompoent"}]}
DEFAULT;
            $page = json_decode( $defaultPage , true);

        }

        if( (  empty($page)   ||  (array_key_exists('list',$page)  && empty($page['list']) )  ) && $key == 5 ){

            $icon = 1;
            //By.jingshuixian   默认个人中心三个菜单    临时解决方案
            $defaultPage=<<<DEFAULT
{"list":[{"title":"搜索栏","type":"search","iconPath":"iconsousuo","isDelete":true,"addNumber":1,"attr":[],"data":{"placeholder":"请输入搜索内容"},"id":1582184892720,"compontents":"houseCompoent"},{"title":"轮播图","type":"banner","icon":"iconlunbo","isDelete":true,"addNumber":9999,"attr":[{"title":"选择模板","type":"ChooseModule","name":"bannerName","data":[{"title":"通屏轮播","name":"banner-tongping","img":"http:\/\/lbqny.migugu.com\/admin\/diy\/banner-tongping.png"}]},{"title":"轮播图高度","type":"InputNumber","name":"style"},{"title":"图片列表","type":"ImageLink","name":"bannerList","isDraggable":true,"isDelete":true,"data":[{"title":"图片","type":"UploadImage","name":"img","desc":"750*350"},{"title":"链接类型","type":"Select","name":"linkType","data":[{"label":"系统内部页面","value":4},{"label":"其他小程序","value":2},{"label":"跳转网页","value":3},{"label":"拨打电话","value":1}]},{"title":"链接地址","type":"Tag","name":"link"}]},{"title":"添加模板","type":"Add","name":"addMouduleName","addNumber":10,"data":[{"link":[{"title":""}],"linkType": 4,"img":[{"url":"http:\/\/lbqny.migugu.com\/admin\/diy\/default.png"}]}]}],"data":{"style":{"number":400,"min":200,"max":800,"label":"请输入","height":400,"whiteSpace":0,"wingBlank":0},"bannerName":"banner-tongping","addMouduleName":"bannerList","bannerList":[]},"id":1582184894981,"compontents":"base"},{"title":"导航","type":"column","icon":"icondaohang1","isDelete":true,"addNumber":9999,"attr":[{"title":"多少行","type":"InputNumber","name":"row"},{"title":"每行多少列","type":"InputNumber","name":"col"},{"title":"图片列表","type":"ImageLink","name":"columnList","isDraggable":true,"isDelete":true,"data":[{"title":"按钮文字","type":"Input","name":"title"},{"title":"图片","type":"UploadImage","name":"img","desc":"100*100"},{"title":"链接类型","type":"Select","name":"linkType","data":[{"label":"系统内部页面","value":4},{"label":"其他小程序","value":2},{"label":"跳转网页","value":3},{"label":"拨打电话","value":1}]},{"title":"链接地址","type":"Tag","name":"link"}]},{"title":"添加模板","type":"Add","name":"addMouduleName","addNumber":16,"data":[{"link":[{"title":""}],"linkType": 4,"img":[{"url":"http:\/\/lbqny.migugu.com\/admin\/diy\/default.png"}]}]}],"data":{"row":{"number":2,"min":1,"max":2},"col":{"number":4,"min":4,"max":5},"style":{"fontColor":"#666","background":"#ffffff","whiteSpace":30,"wingBlank":0},"addMouduleName":"columnList","columnList":[]},"id":1582184896039,"compontents":"base"},{"title":"房源列表","type":"houseList","iconPath":"iconfangyuanlist","isDelete":true,"addNumber":1,"attr":[{"title":"获取方式","type":"Radio","name":"getType","data":[{"label":2,"title":"自动"}]}],"data":{"getType":2,"houseList":[]},"id":1582184897729,"compontents":"houseCompoent"}]}
DEFAULT;
            $page = json_decode( $defaultPage , true);

        }

        if (!empty($page['list'])) {

            if(!empty($this->isdouyin)){

                foreach ($page['list'] as $ks => $items) {

                    if(!in_array($items['type'],['moduleMenuShopOrder','moduleMenuShop'])){

                        $list [] = $items;
                    }

                }

                $page['list'] = $list;

            }


            foreach ($page['list'] as $k => $item) {
                //房源banner
                if($key == 5&&$item['type'] =='banner'&&empty($item['data']['bannerList'])){
                    //房产banner模型
                    $banner_model = new AdminBanner();
                    //查询所有上架的banner
                    $banner       = $banner_model->where(['uniacid'=>$this->_uniacid,'status'=>1])->order('top desc,id desc')->select();
                    //循环
                    $new_banner = [];
                    if(!empty($banner)){
                        foreach ($banner as $kb => $vb){
                            //文字
                            $new_banner[$kb]['link'][0]['title'] = '';
                            //链接
                            $new_banner[$kb]['link'][0]['url']   = $vb['link'];
                            //链接类型
                            $new_banner[$kb]['linkType']         = $vb['link_type'];
                            //图片链接
                            $new_banner[$kb]['img'][0]['url']    = $vb['path'];
                        }
                    }
                    $page['list'][$k]['data']['bannerList'] = $new_banner;
                }

                //房源
                if($key == 5&&$item['type'] =='houseList'&&empty($item['data']['houseList'])) {
                    //房源模型
                    $house_model = new \app\house\model\IndexHouse();

                    if( !empty($icon)&&$icon==1){

                        $page['list'][$k]['data']['houseList'] = $house_model->where(['uniacid'=>$this->_uniacid,'status'=>1])->order('top desc,id desc')->paginate(20)->toArray();

                        $page['list'][$k]['data']['isShowAddr']= true;
                    }else{
                        //房源列表 一页十条
                        $house_cate = !empty($page['list'][$k]['data']['category'])?$page['list'][$k]['data']['category']:0;

                        $page['list'][$k]['data']['houseList'] = $house_model->houseList(['uniacid'=>$this->_uniacid,'status'=>1,'category'=>$house_cate],$page['list'][$k]['data']['limit']['number']);
                    }

                }
                //房源分类
                if($key == 5&&$item['type'] =='column'&&empty($item['data']['columnList'])) {
                    //房源分类模型
                    $cate_model = new AdminCate();
                    //房源分类列表
                    $columnList = $cate_model->where(['uniacid'=>$this->_uniacid,'status'=>1])->order('top desc,id desc')->select()->toArray();

                    $columnList = transImagesOne($columnList,['img']);
                    //循环
                    $new_column = [];

                    if(!empty($columnList)){
                        foreach ($columnList as $kb => $vb){
                            //标题
                            $new_column[$kb]['title']            = $vb['title'];
                            //文字
                            $new_column[$kb]['link'][0]['title'] = $vb['title'];
                            //链接
                            $new_column[$kb]['link'][0]['url']   = '/house/pages/filter/filter?id='.$vb['id'].'&title='.$vb['title'];;
                            //链接类型
                            $new_column[$kb]['linkType']         = 4;
                            //图片链接
                            $new_column[$kb]['img'][0]['url']    = $vb['img'];
                        }
                    }

                    $page['list'][$k]['data']['columnList'] = $new_column;
                }


                if(!empty($item['data']['list'])){

                    foreach ($item['data']['list'] as $ks => $vs){

                        if(!empty($vs['link']['url'])&&strpos($vs['link']['url'],'?staff_id=') !== false&&!empty($this->_param['staff_id'])){

                            $page['list'][$k]['data']['list'][$ks]['link']['url'] = str_replace('?staff_id=0','?staff_id=',$page['list'][$k]['data']['list'][$ks]['link']['url']);

                            $page['list'][$k]['data']['list'][$ks]['link']['url'].= $this->_param['staff_id'];

                            $item['data']['list'][$ks]['link']['url'] = str_replace('?staff_id=0','?staff_id=',$item['data']['list'][$ks]['link']['url']);

                            $item['data']['list'][$ks]['link']['url'].= $this->_param['staff_id'];

                        }
                    }
                }
                //判断有没有d商城
                if($key==20001){

                    $tab = json_decode($diy_data['tabbar'],true);


                    $tab_key = array_column($tab['list'],'key');

                    $item['shop_auth'] = in_array(2,$tab_key);


                }
                //老版本
                if (array_key_exists('params', $item)) {


                    $params = $item['params'];

                    $getType = $params['getType'];

                    if ($getType !== 2) {
                        continue;
                    }

                    $number = $params['number'];
                    $sort = $params['sort'];
                    $sort_filed_map = [
                        0 => 'sort',
                        1 => 'iv',
                        2 => 'collect'
                    ];
                    $sort_filed = $sort_filed_map[$sort] ?? 'id';

                    $update_item = $item;
                    $type = $item['type'];
                    switch ($type) {
                        case "site" :
                            $m = new IndexSite();
                            $update_item['data'] = $m->where([['uniacid', '=', $this->_uniacid], ['status', '=', 1]])->order($sort_filed, 'desc')->limit($number)->select();
                            $page['list'][$k] = $update_item;
                            break;
                        case "case" :
                            $m = new IndexCase();
                            $update_item['data'] = $m->where([['uniacid', '=', $this->_uniacid], ['status', '=', 1], ['recommend', '=', 1]])->order($sort_filed, 'desc')->limit($number)->select();
                            $page['list'][$k] = $update_item;
                            break;
                        case "strategy" :
                            $m = new IndexNews();
                            $update_item['data'] = $m->where([['uniacid', '=', $this->_uniacid], ['status', '=', 1]])->order($sort_filed, 'desc')->limit($number)->select();
                            $page['list'][$k] = $update_item;
                            break;
                    }

                } else { //新版本

                    $type = $item['type'];
                    //目前是根据Type来自动激活事件,后期可以给组件自定义  DataSubscribe=>'' , 自定义监听名称,来相应对应数据
                    $type = 'Diy' . ucfirst($type);

                    $item['staff_id'] = !empty($input['staff_id'])?$input['staff_id']:0;

                    $result = event($type, $item);
                    //判断监听者相应数据是否正确
                    if (!empty($result)) {
                        $page['list'][$k] = $result[0];
                    }

                }



            }

        }

        $diy_data['page'] = $page;

        return $this->success($diy_data);
    }


    /**
     * 获取员工端推广中心菜单
     *
     * @author shuixian
     * @DataTime: 2019/12/13 10:38
     */
    public function getWorkCenterMenu(){

        $addWorkCenterToolsMenu =  event('AddWorkCenterToolsMenu');

        $list = [
            "title" =>  '工具箱',
            "desc" =>  '量身定制您的日常工具',
            "show" => true,
            "row"  => 4,
            "list" =>[]
        ];
        $icons = [] ;
        foreach ($addWorkCenterToolsMenu as $item){

            $icons = array_merge($icons,$item);
        }


        $list["list"] = $icons ;
        $list = [$list] ;
        $AddWorkCenterModelMenu =  event('AddWorkCenterModelMenu');

        foreach ($AddWorkCenterModelMenu as $item){

            $list = array_merge($list,$item);
        }



        //用户中心菜单
        $addWorkStaffCenterMenu =  event('AddWorkStaffCenterMenu');
        $staff_center_menu = [] ;
        foreach ($addWorkStaffCenterMenu as $item){
            $staff_center_menu = array_merge($staff_center_menu,$item);
        }


        $result = [];
        $result['staff_center_menu'] = $staff_center_menu;

        if(!empty($this->isdouyin)){

//            dump($list);exit;
            foreach ($list as $ks => $vs){

                $arrs = [];

                foreach ($vs['list'] as $vv){

                    if(!in_array($vv['title'],['获客海报','我的收入','订单管理','退款管理','卡券管理'])){

                        $arrs[] = $vv;
                    }

                }

                $list[$ks]['list'] = $arrs;

            }

        }

        $result['work_center_menu'] = $list;

        return $this->success($result);

    }




}